package com.hncboy.chatgpt.front.api.baidu;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.util.HashMap;
import java.util.Map;


public class TransApi {

    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private static final String APP_ID = "20221017001397005";
    private static final String SECURITY_KEY = "cIUPvb2lcakVsXBrKEIF";


    public String getTransResult(String query) {
        Map<String, String> params = buildParams(query, "en", "zh");
        String s = HttpGet.get(TRANS_API_HOST, params);
        JSONObject textJsonObject = JSONUtil.parseObj(s);
        JSONArray transResult = (JSONArray) textJsonObject.get("trans_result");
        Object jsonData = transResult.get(0);
        JSONObject jsonObject = JSONUtil.parseObj(jsonData);
        //dst是翻译过的结果
        String dst = (String) jsonObject.get("dst");
        return dst;
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", APP_ID);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文
        params.put("sign", MD5.md5(src));
        return params;
    }

}
